<template>
  <div class="club-applications">
    <el-table :data="paginatedApplications" style="width: 100%">
      <el-table-column prop="id" label="申请编号" width="100" />
      <el-table-column
          prop="type"
          label="申请类型"
          width="120"
          :filters="applicationTypeFilters"
          :filter-method="filterType"
          filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getApplicationTypeColor(row.type)">{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="targetId" label="目标社团/活动编号" width="150" />
      <el-table-column prop="targetName" label="目标社团/活动名" width="180" />
      <el-table-column
        prop="applicantUsername"
        label="申请人用户名"
        width="150"
      />
      <el-table-column
          prop="status"
          label="申请审核状态"
          width="130"
          :filters="statusFilters"
          :filter-method="filterStatus"
          filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请发出时间" width="150" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="handleDetails(row)">详情</el-button>
          <el-button
            v-if="isButtonCanShow(row.status)"
            size="small"
            type="success"
            @click="handleApprove(row)"
          >
            通过
          </el-button>
          <el-button
            v-if="isButtonCanShow(row.status)"
            size="small"
            type="danger"
            @click="handleReject(row)"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-size="pageSize"
        :total="totalApplications"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewDialogTitle"
      width="30%"
  >
    <el-input
        v-model="reviewContent"
        type="textarea"
        :rows="4"
        placeholder="请输入审核意见（选填）"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {type Action, ElMessage, ElMessageBox} from "element-plus";
import {
  type ReviewConsequence,
  ReviewControllerService,
  UserApplicationControllerService,
  type UserApplicationQueryRequest,
  type UserApplicationVO,
} from "../../../../generated";
import {useRouter} from "vue-router";
import {useUserStore} from "../../../stores/user.ts";

interface ShowedApplication {
  id: number;
  typeCode: number;
  type: string;
  targetId: number;
  targetName: string;
  applicantUsername: string;
  status: string;
  applyTime: string;
}

const applications = ref<ShowedApplication[]>([]);

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "待审核":
      return "warning";
    case "通过":
      return "success";
    case "拒绝":
      return "danger";
    default:
      return "info";
  }
};

const getApplicationType = (type: number): string => {
  switch (type) {
    case 1:
      return "加入社团";
    case 2:
      return "退出社团";
    case 3:
      return "参加活动";
    case 4:
      return "退出活动";
    default:
      return "";
  }
};

const getApplicationTypeColor = (type: string): string => {
  switch (type) {
    case '退出社团':
    case '退出活动':
      return 'danger';
    case '加入社团':
      return 'success';
    case '参加活动':
      return 'primary';
    default:
      return 'info';
  }
};

const queryRequest = ref<UserApplicationQueryRequest>({
  pageSize: 10,
  current: 1,
});

const loadData = async () => {
  try {
    const res = await UserApplicationControllerService.listApplicationVoByPage(
      queryRequest.value,
    );
    if (res.code === 0 && res.data?.records) {
      const applicationVoList = res.data.records as UserApplicationVO[];
      applications.value = applicationVoList.map(
        (applicationVo) =>
          ({
            id: applicationVo.id,
            typeCode: applicationVo.type as number,
            type: getApplicationType(applicationVo.type as number),
            targetId: applicationVo.additionalInfo,
            targetName: applicationVo.targetName,
            applicantUsername: applicationVo.userVO?.userName,
            status: applicationVo.reviewVO?.result,
            applyTime: applicationVo.createTime,
          }) as ShowedApplication,
      );
      currentPage.value = 1;
    } else {
      applications.value = [];
      ElMessage.error("加载数据失败：" + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
    applications.value = [];
  }
};

onMounted(() => {
  loadData();
});

// 定义申请类型筛选选项
const applicationTypeFilters = [
  { text: '加入社团', value: '加入社团' },
  { text: '退出社团', value: '退出社团' },
  { text: '参加活动', value: '参加活动' },
  { text: '退出活动', value: '退出活动' },
];

// 筛选申请类型方法
const filterType = (value: string, row: ShowedApplication) => {
  return row.type === value;
};

// 定义状态筛选选项
const statusFilters = [
  { text: '待审核', value: '待审核' },
  { text: '通过', value: '通过' },
  { text: '拒绝', value: '拒绝' },
];

// 筛选审核状态方法
const filterStatus = (value: string, row: ShowedApplication) => {
  return row.status === value;
};

// 计算当前页的数据列表
const paginatedApplications = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredApplications.value.slice(startIndex, endIndex);
});

const filteredApplications = computed(() => {
  return applications.value;
});

const currentPage = ref(1);
const pageSize = ref(10);
const totalApplications = computed(() => filteredApplications.value.length); // 计算总数据数
const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const isBatchMode = ref(false);
const isButtonCanShow = (status: string) => {
  if (isBatchMode.value === true) {
    return false;
  } else {
    return status === "待审核";
  }
};

const router = useRouter();
// 处理详情按钮点击事件
const handleDetails = (row: UserApplicationVO) => {
  router.push({
    path: "/manager/application/user/info",
    query: { id: row.id },
  });
};

const userStore = useUserStore();
const reviewDialogVisible = ref(false);
const reviewDialogTitle = ref("");
const reviewContent = ref("");
const currentReviewType = ref<"approve" | "reject">("approve");
const currentReviewRow = ref<ShowedApplication | null>(null);

//处理通过按钮点击事件
const handleApprove = (row: ShowedApplication) => {
  currentReviewType.value = "approve";
  currentReviewRow.value = row;
  reviewDialogTitle.value = "通过申请";
  reviewDialogVisible.value = true;
};

// 处理拒绝按钮点击事件
const handleReject = (row: ShowedApplication) => {
  currentReviewType.value = "reject";
  currentReviewRow.value = row;
  reviewDialogTitle.value = "拒绝申请";
  reviewDialogVisible.value = true;
};

// 提交审核结果
const submitReview = async () => {
  if (!currentReviewRow.value) return;

  const row = currentReviewRow.value;
  const result = currentReviewType.value === "approve" ?1 : 2;

  try {
    const accessApplicationRes = await ReviewControllerService.doReview({
      userId: userStore.id,
      type: row.typeCode,
      applicationId: row.id,
      content: reviewContent.value,
      result: result,
    } as ReviewConsequence);

    if (accessApplicationRes.code === 0) {
      const actionText = result === 1 ? "通过" : "拒绝";
      const successStr = `申请 ${row.id} 已成功${actionText}`;
      ElMessageBox.alert(successStr, `${actionText}成功`, {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            window.location.reload(); // 刷新当前页面
          }
        },
      });
    } else {
      const errorStr = "错误原因: " + accessApplicationRes.message;
      ElMessageBox.alert(errorStr, "操作失败", {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            window.location.reload(); // 刷新当前页面
          }
        },
      });
    }
  } catch (error) {
    console.error("提交审核结果时发生错误:", error);
    ElMessage.error("提交审核结果时发生错误，请稍后重试");
  } finally {
    reviewDialogVisible.value = false;
    reviewContent.value = "";
    currentReviewRow.value = null;
  }
};
</script>

<style scoped>
.club-applications {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
